﻿using System;
using System.Collections.Generic;
using System.Linq;

namespace ICommonLibrary.Security {

    public class Base36 {

        private const string CharList = "0123456789abcdefghijklmnopqrstuvwxyz";

        public static String Encode(long input) {
            if (input < 0) {
                throw new ArgumentOutOfRangeException("input", input, "input cannot be negative");
            }

            var result = new Stack<char>(16);
            while (input != 0) {
                result.Push(CharList[(int)(input % 36)]);
                input /= 36;
            }
            return new string(result.ToArray());
        }

        /// <summary>
        /// Decode the Base36 Encoded string into a number
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public static long Decode(string input) {
            var reversed = input.ToLower().Reverse();
            long result = 0;
            int pos = 0;
            foreach (char c in reversed) {
                result += CharList.IndexOf(c) * (long)Math.Pow(36, pos);
                pos++;
            }
            return result;
        }
         
    }
}